import { View, Text, ScrollView } from "@tarojs/components";
import { useLoad } from "@tarojs/taro";
import "./index.module.scss";
import request from '@/utils/utils.js'
// 导入必要的依赖
import React, { useState, useEffect } from "react";
import Taro from "@tarojs/taro";

// 支出分类图标组件
const CategoryIcon = ({ icon, label, selected, onClick }) => (
  <View
    className={`category-icon ${selected ? "selected" : ""}`}
    onClick={onClick}
  >
    <View className="icon">{icon}</View>
    <Text className="label">{label}</Text>
  </View>
);

// 数字键盘按钮组件
const KeypadButton = ({ value, onClick, className = "" }) => (
  <View className={`keypad-button ${className}`} onClick={() => onClick(value)}>
    {value}
  </View>
);

// 主页面组件
export default function ExpenseTracker() {
  // 状态管理
  const [displayValue, setDisplayValue] = useState("0"); // 显示值
  const [storedValue, setStoredValue] = useState(null); // 存储的值
  const [selectedCategory, setSelectedCategory] = useState("饮食");
  const [operator, setOperator] = useState(null); // 当前运算符
  const [waitingForOperand, setWaitingForOperand] = useState(false); // 是否等待输入新数字
  const [userId, setUserId] = useState("");
  // 支出分类数据
  const categories = [
    { id: "uncategorized", icon: "📑", label: "未分组" },
    { id: "food", icon: "🍔", label: "饮食" },
    { id: "daily", icon: "🏠", label: "日用" },
    { id: "transport", icon: "🚌", label: "交通" },
    { id: "social", icon: "🥂", label: "社交" },
    { id: "housing", icon: "🏘️", label: "住房物业" },
    { id: "gift", icon: "🎁", label: "礼物" },
    { id: "communication", icon: "📱", label: "通信" },
    { id: "clothing", icon: "👔", label: "服饰" },
    { id: "entertainment", icon: "🎬", label: "娱乐" },
    { id: "beauty", icon: "💇", label: "美容" },
    { id: "medical", icon: "🏥", label: "医疗" },
    { id: "tax", icon: "💰", label: "税金" },
    { id: "education", icon: "🎓", label: "教育" },
    { id: "baby", icon: "👶", label: "宝宝" },
    { id: "pets", icon: "🐱", label: "宠物" },
    { id: "travel", icon: "✈️", label: "旅行" },
  ];
  // Initialize userId on component mount
  useEffect(() => {
    const initializeUserId = () => {
      try {
        const storedUserId = Taro.getStorageSync("userId");
        if (storedUserId) {
          setUserId(storedUserId);
        } else {
          const newUserId = generateUserId();
          Taro.setStorageSync("userId", newUserId);
          setUserId(newUserId);
        }
      } catch (error) {
        console.error("Error handling userId:", error);
        // If there's an error, generate a new ID anyway to ensure functionality
        const fallbackId = generateUserId();
        setUserId(fallbackId);
        try {
          Taro.setStorageSync("userId", fallbackId);
        } catch (storageError) {
          console.error("Error saving to storage:", storageError);
        }
      }
    };

    initializeUserId();
  }, []);
  // 计算结果
  const calculate = (a, b, op) => {
    a = parseFloat(a);
    b = parseFloat(b);
    switch (op) {
      case "+":
        return a + b;
      case "-":
        return a - b;
      case "×":
        return a * b;
      case "÷":
        return b !== 0 ? a / b : "Error";
      default:
        return b;
    }
  };
  //保存记账
  
  const handleSubmit = async () => {
    // 检查是否选择了支出类型
    if (selectedCategory === '') {
      Taro.showToast({
        title: '请选择支出类型',
        icon: 'none',
        duration: 2000
      });
      return;
    }
  
    // 检查是否填写了支出金额
    if (displayValue === '0') {
      Taro.showToast({
        title: '请填写支出金额',
        icon: 'none',
        duration: 2000
      });
      return;
    }
  
    // 准备请求数据
    const transactionData = {
      user_id: userId,
      amount: parseFloat(displayValue),
      category: selectedCategory,
      description: "" // 如果有描述字段，可以添加
    };
  
    // 调用接口
    try {
      const result = await request({
        url: 'http://43.143.236.218:8080/transaction',
        method: 'POST',
        data: transactionData,
        header: {
          'content-type': 'application/json'
        }
      });
  
      if (result.success) {
        Taro.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        });
        // 重置状态
        handleClear();
        setSelectedCategory('');
      } else {
        throw new Error(result.message || '提交失败');
      }
    } catch (error) {
      console.error('Error submitting expense:', error);
      Taro.showToast({
        title: error.message || '提交失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  };
  //获取记账历史
  const getTransactions = async () => {
    try {
      const result = await request({
        url: 'http://43.143.236.218:8080/transactions',
        method: 'GET',
        data: { user_id: userId }
      });
  
      if (result.success) {
        // 处理获取到的交易记录
        setTransactions(result.data);
      } else {
        throw new Error(result.message || '获取交易记录失败');
      }
    } catch (error) {
      console.error('Error fetching transactions:', error);
      Taro.showToast({
        title: error.message || '获取交易记录失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  };
  

  // Generate random user ID function
  const generateUserId = () => {
    const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const numbers = "0123456789";
    const firstChar = letters[Math.floor(Math.random() * letters.length)];
    const length = Math.floor(Math.random() * 7) + 1; // Random length between 1-7 (plus first letter = 2-8)
    let result = firstChar;
    const allChars = letters + numbers;

    for (let i = 0; i < length; i++) {
      result += allChars[Math.floor(Math.random() * allChars.length)];
    }

    return result;
  };
  // 处理数字输入
  const handleNumber = (num) => {
    if (waitingForOperand) {
      setDisplayValue(String(num));
      setWaitingForOperand(false);
    } else {
      setDisplayValue(displayValue === "0" ? String(num) : displayValue + num);
    }
  };
  // 新增状态来存储 IP 信息
  const [ipInfo, setIpInfo] = useState(null);

  // 使用 useEffect 在组件挂载后获取 IP 信息
  useEffect(() => {
    const fetchIpInfo = async () => {
      try {
        const response = await Taro.request({
          url: "http://43.143.236.218:8080/visitip",
          method: "GET",
        });
        setIpInfo(response.data);
      } catch (error) {
        console.error("Error fetching IP info:", error);
      }
    };

    fetchIpInfo();
  }, []);
  // 处理运算符
  const handleOperator = (op) => {
    const currentValue = parseFloat(displayValue);

    if (storedValue === null) {
      setStoredValue(currentValue);
    } else if (operator && !waitingForOperand) {
      const result = calculate(storedValue, currentValue, operator);
      setDisplayValue(String(result));
      setStoredValue(result);
    }

    setOperator(op);
    setWaitingForOperand(true);
  };

  // 处理等号
  const handleEquals = () => {
    const currentValue = parseFloat(displayValue);

    if (operator && storedValue !== null) {
      const result = calculate(storedValue, currentValue, operator);
      setDisplayValue(String(result));
      setStoredValue(null);
      setOperator(null);
      setWaitingForOperand(true);
    }
  };

  // 处理删除
  const handleDelete = () => {
    if (waitingForOperand) return;
    setDisplayValue((prev) => {
      if (prev.length === 1) return "0";
      return prev.slice(0, -1);
    });
  };

  // 处理清除
  const handleClear = () => {
    setDisplayValue("0");
    setStoredValue(null);
    setOperator(null);
    setWaitingForOperand(false);
  };

  return (
    <View className="expense-tracker">
       <View className="footer-btn" onClick={() => Taro.navigateTo({ url: '/pages/index/index' })}> 
        back
       </View>
      注册账号
      已有账号去登录
      
      
    </View>
  );
}
